class LevelEditor {
    constructor() {
        this.canvas = document.getElementById('editorCanvas');
        this.ctx = this.canvas.getContext('2d');
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.gridSize = 40;
        this.cols = this.width / this.gridSize;
        this.rows = this.height / this.gridSize;
        
        this.currentTool = 'brick';
        this.levelData = {
            blocks: [],
            player: null,
            enemies: []
        };
        
        this.isDrawing = false;
        
        this.initEventListeners();
        this.render();
    }
    
    initEventListeners() {
        // 工具选择
        document.querySelectorAll('.tool-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                document.querySelectorAll('.tool-btn').forEach(b => b.classList.remove('active'));
                e.target.classList.add('active');
                this.currentTool = e.target.dataset.tool;
            });
        });
        
        // 画布事件
        this.canvas.addEventListener('mousedown', (e) => {
            this.isDrawing = true;
            this.handleCanvasClick(e);
        });
        
        this.canvas.addEventListener('mousemove', (e) => {
            if (this.isDrawing) {
                this.handleCanvasClick(e);
            }
        });
        
        this.canvas.addEventListener('mouseup', () => {
            this.isDrawing = false;
        });
        
        this.canvas.addEventListener('mouseleave', () => {
            this.isDrawing = false;
        });
    }
    
    handleCanvasClick(e) {
        const rect = this.canvas.getBoundingClientRect();
        const x = Math.floor((e.clientX - rect.left) / this.gridSize);
        const y = Math.floor((e.clientY - rect.top) / this.gridSize);
        
        if (x < 0 || x >= this.cols || y < 0 || y >= this.rows) return;
        
        switch (this.currentTool) {
            case 'player':
                this.levelData.player = {x, y};
                break;
            case 'enemy':
                // 避免重复添加
                if (!this.levelData.enemies.find(e => e.x === x && e.y === y)) {
                    this.levelData.enemies.push({x, y});
                }
                break;
            case 'erase':
                this.levelData.blocks = this.levelData.blocks.filter(b => !(b.x === x && b.y === y));
                this.levelData.enemies = this.levelData.enemies.filter(e => !(e.x === x && e.y === y));
                if (this.levelData.player && this.levelData.player.x === x && this.levelData.player.y === y) {
                    this.levelData.player = null;
                }
                break;
            default:
                // 避免重复添加
                if (!this.levelData.blocks.find(b => b.x === x && b.y === y)) {
                    this.levelData.blocks.push({x, y, type: this.currentTool});
                }
                break;
        }
        
        this.render();
    }
    
    render() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        // 绘制网格
        this.drawGrid();
        
        // 绘制已有元素
        this.levelData.blocks.forEach(block => this.drawBlock(block));
        
        if (this.levelData.player) {
            this.drawPlayer();
        }
        
        this.levelData.enemies.forEach(enemy => this.drawEnemy(enemy));
    }
    
    drawGrid() {
        this.ctx.strokeStyle = '#2c3e50';
        this.ctx.lineWidth = 1;
        
        for (let x = 0; x <= this.width; x += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, 0);
            this.ctx.lineTo(x, this.height);
            this.ctx.stroke();
        }
        
        for (let y = 0; y <= this.height; y += this.gridSize) {
            this.ctx.beginPath();
            this.ctx.moveTo(0, y);
            this.ctx.lineTo(this.width, y);
            this.ctx.stroke();
        }
    }
    
    drawBlock(block) {
        const colors = {
            'brick': '#8B4513',
            'steel': '#708090',
            'water': '#4682B4',
            'forest': '#228B22',
            'base': '#FFD700'
        };
        
        this.ctx.fillStyle = colors[block.type] || '#808080';
        this.ctx.fillRect(
            block.x * this.gridSize, 
            block.y * this.gridSize, 
            this.gridSize, 
            this.gridSize
        );
        
        this.ctx.strokeStyle = '#2c3e50';
        this.ctx.strokeRect(
            block.x * this.gridSize, 
            block.y * this.gridSize, 
            this.gridSize, 
            this.gridSize
        );
    }
    
    drawPlayer() {
        const x = this.levelData.player.x * this.gridSize;
        const y = this.levelData.player.y * this.gridSize;
        
        this.ctx.fillStyle = '#3498db';
        this.ctx.fillRect(x, y, this.gridSize, this.gridSize);
        
        this.ctx.fillStyle = 'white';
        this.ctx.font = '20px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.fillText('P', x + this.gridSize/2, y + this.gridSize/2 + 7);
    }
    
    drawEnemy(enemy) {
        const x = enemy.x * this.gridSize;
        const y = enemy.y * this.gridSize;
        
        this.ctx.fillStyle = '#e74c3c';
        this.ctx.fillRect(x, y, this.gridSize, this.gridSize);
        
        this.ctx.fillStyle = 'white';
        this.ctx.font = '20px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.fillText('E', x + this.gridSize/2, y + this.gridSize/2 + 7);
    }
    
    clear() {
        this.levelData = {
            blocks: [],
            player: null,
            enemies: []
        };
        this.render();
    }
    
    save() {
        if (!this.levelData.player) {
            alert('请设置玩家出生点！');
            return;
        }
        
        const levelCode = btoa(JSON.stringify(this.levelData));
        localStorage.setItem('customLevel', levelCode);
        
        // 创建可分享的代码
        const shareCode = levelCode.substring(0, 20) + '...';
        prompt('关卡已保存！分享代码：', shareCode);
    }
    
    load() {
        const levelCode = prompt('请输入关卡代码：');
        if (!levelCode) return;
        
        try {
            const decoded = atob(levelCode);
            this.levelData = JSON.parse(decoded);
            this.render();
            alert('关卡加载成功！');
        } catch (e) {
            alert('无效的关卡代码！');
        }
    }
    
    test() {
        if (!this.levelData.player) {
            alert('请设置玩家出生点！');
            return;
        }
        
        showGame();
        game.startGame(this.levelData);
    }
}

// 全局编辑器实例
let editor = null;

// 初始化编辑器
function initEditor() {
    if (!editor) {
        editor = new LevelEditor();
    }
}

// 全局函数
function clearLevel() {
    if (editor) editor.clear();
}

function saveLevel() {
    if (editor) editor.save();
}

function loadLevel() {
    if (editor) editor.load();
}

function testLevel() {
    if (editor) editor.test();
}
